
const beforeRequest = (auth,header={})=>{
	let pass = true
	if(auth){
		// 验证token
		const token = uni.getStorageSync('token')
		// 验证不通过则pass=false
		if(token){
			header['authorization'] = 'bearer'+token
		}else{
			/* uni.showToast({
				title: '未登录或登录凭据已过期，请重新登录',
				icon:'error',
				duration: 1000
			}); */// token验证失败则不可请求 */
			pass = false
			uni.navigateTo({
				url:'/pages/avatar/login'
			})
		}
	}
	return pass
}
const request = ({url,method,data,header,auth})=>{
	const baseUrl = 'http://localhost:8080'
	return new Promise((resolve,reject)=>{
		const pass = beforeRequest(auth,header)
		if(!pass){
			return
		}
		uni.request({
			url:`${baseUrl}${url}`,
			timeout:3000,
			method:method||'GET',
			data:data,
			header: header||{'content-type': 'application/json'},
			success: (res) => {
				resolve(res.data)
			},
			fail:(err)=>{
				reject(err)
			}
		})
		// 相当于 success 用以下方法uni.request()中传递的对象中不能有sucess/fail属性
		// .then(res=>{
		// 	console.log(113,res)
		// })
		// 相当于 fail
		// .catch(err=>{
		// 	console.log(223,err)
		// })
	})
}

// get请求
const get = ({url,data,header,auth})=>{
	return request({
		url:url,
		data:data,
		header:header,
		auth
	})
}

// post请求
const post = ({url,data,header,auth})=>{
	return request({
		url:url,
		method:'POST',
		data:data,
		header:header,
		auth:auth
	})
}

// put请求
const put = ({url,data,header,auth})=>{
	return request({
		url:url,
		method:'PUT',
		data:data,
		header:header,
		auth:auth
	})
}

// delete请求
const del = ({url,data,header,auth})=>{
	return request({
		url:url,
		method:'DELETE',
		data:data,
		header:header,
		auth:auth
	})
}

export default {
	get,
	post,
	put,
	del
}